package keer.httpinterface.proxy;

import keer.httpinterface.HttpInterfaceException;
import keer.httpinterface.http.HttpRequester;
import keer.httpinterface.utils.HttpInterfaceFactories;

/**
 * ProxyFactory接口用于创建代理对象
 * 它定义了如何根据目标类和HTTP请求器创建一个代理实例
 * @see HttpRequester
 *
 * @author Keer
 * @since 1.0.0
 */
public interface ProxyFactory {
    /**
     * 创建一个指定类的代理实例
     *
     * @param <T> 目标类的类型
     * @param targetClass 目标类的Class对象
     * @param requester HTTP请求器，用于处理HTTP请求
     * @return 返回创建的代理实例
     * @throws HttpInterfaceException 如果创建代理过程中发生错误
     */
    <T> T createProxy(Class<T> targetClass, HttpRequester requester) throws HttpInterfaceException;

    /**
     * 根据类加载器获取ProxyFactory的实例
     *
     * @param classLoader 类加载器，用于加载类
     * @return 返回ProxyFactory的一个实例
     * @throws HttpInterfaceException 如果创建代理工厂失败
     */
    static ProxyFactory getInstance(ClassLoader classLoader) throws HttpInterfaceException {
        ProxyFactory proxyFactory = null;
        try {
            // 尝试加载并创建最后一个已知的ProxyFactory实例
            proxyFactory = HttpInterfaceFactories.loadLastOneFactoryInstance(classLoader, ProxyFactory.class);
        } catch (Exception e) {
            // 如果加载过程中发生异常，抛出自定义异常
            throw new HttpInterfaceException("Create proxy factory fail.", e);
        }
        // 如果proxyFactory仍然为null，创建一个默认的JdkHttpInterfaceProxyFactory实例
        if (proxyFactory == null) {
            proxyFactory = new JdkHttpInterfaceProxyFactory();
        }
        return proxyFactory;
    }

    /**
     * 获取ProxyFactory的实例，使用当前线程的上下文类加载器
     *
     * @return 返回ProxyFactory的一个实例
     * @throws HttpInterfaceException 如果创建代理工厂失败
     */
    static ProxyFactory getInstance() throws HttpInterfaceException {
        // 使用当前线程的上下文类加载器获取ProxyFactory实例
        return getInstance(Thread.currentThread().getContextClassLoader());
    }
}
